package com.yungu.swift.admin.handler;

import com.google.common.collect.Lists;
import com.yungu.swift.admin.base.GatewayHeader;
import com.yungu.swift.admin.consts.GatewayErrorEnum;
import com.yungu.swift.admin.route.common.LogicAdmin;
import com.yungu.swift.autoconfig.redis.RedisStringCacheService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.Md5Utils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by cuixiuyin on 2016/12/8.
 * 用户鉴权方案
 */
@Slf4j
public class TokenHandler extends HandlerInterceptorAdapter {

    private static final List<String> SUPPORT_TYPE = Lists.newArrayList("GET", "POST");


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        if (!SUPPORT_TYPE.contains(request.getMethod())) {
            GatewayErrorEnum notSupportMethod = GatewayErrorEnum.NOT_SUPPORT_METHOD;
            response.getWriter().print(JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(notSupportMethod.getCode(), notSupportMethod.getMsg())));
            return false;
        }
        String accessToken = request.getHeader(GatewayHeader.accessToken);
        // 判断 accessToken 状态
        if (StringUtils.isEmpty(accessToken)) {
            GatewayErrorEnum loginTokenLack = GatewayErrorEnum.LOGIN_TOKEN_LACK;
            response.getWriter().print(JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(loginTokenLack.getCode(), loginTokenLack.getMsg())));
            return false;
        }
        RedisStringCacheService redisStringCacheService = SpringContextHolder.getBean(RedisStringCacheService.class);
        String cacheKey = redisStringCacheService.get(LogicAdmin.ACCESS_TOKEN_PREFFIX + Md5Utils.encode(accessToken));
        if (StringUtils.isEmpty(cacheKey)) {
            GatewayErrorEnum tokenInvalid = GatewayErrorEnum.LOGIN_TOKEN_INVALID;
            response.getWriter().print(JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(tokenInvalid.getCode(), tokenInvalid.getMsg())));
            return false;
        }
        return true;
    }
}
